package com.zhangjingcheng.yunyixia.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhangjingcheng.yunyixia.em.UpdateSpaceType;
import com.zhangjingcheng.yunyixia.mapper.FileMapper;
import com.zhangjingcheng.yunyixia.mapper.ShareMapper;
import com.zhangjingcheng.yunyixia.mapper.StoreMapper;
import com.zhangjingcheng.yunyixia.pojo.entity.FileInfo;
import com.zhangjingcheng.yunyixia.pojo.entity.Share;
import com.zhangjingcheng.yunyixia.pojo.entity.Store;
import com.zhangjingcheng.yunyixia.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class CleanTask {

    @Autowired
    private ShareMapper shareMapper;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private FileService fileService;

    /**
     * 定时任务，每天凌晨1点清理过期的分享文件
     */
    @Scheduled(cron = "0 0 1 * * *")
    protected void cleanShare(){
        LambdaQueryWrapper<Share> queryWrapper = new LambdaQueryWrapper<Share>()
                .lt(Share::getExpireTime, LocalDateTime.now());
        shareMapper.delete(queryWrapper);
    }

    /**
     * 定时任务，每天凌晨1点清理过时的回收站文件
     */
    @Scheduled(cron = "0 0 2 * * *")
    @Transactional
    protected void cleanRecycle(){
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<Store>()
                .ne(Store::getRecoverTime, null)
                .lt(Store::getRecoverTime, LocalDateTime.now().minusDays(10));
        List<Store> storeList = storeMapper.selectList(queryWrapper);
        storeList.forEach(store -> {
            //找出关联文件
            FileInfo file = fileMapper.selectById(store.getFileId());
            //得到文件大小
            Long size = file.getSize();
            //更新用户空间
            fileService.updateUserSpace(store.getUserId(),size, UpdateSpaceType.SUB.name());
            storeMapper.deleteById(store);
        });
    }
}
